<?php

namespace App\Http\Services\Admin;

use App\Exceptions\Fail;
use App\Http\Services\Service;
use App\Models\Admin\RoleModel;
use App\Models\Admin\UserModel;
use Illuminate\Support\Facades\DB;

class UserService implements Service
{
    /**
     * 列表
     */
    public function index(array $params = []): array
    {
        return UserModel::all()->toArray();
    }

    /**
     * 分页列表
     */
    public function table(int $page, int $pageSize, array $params): array
    {
        $roleModel = UserModel::query()
            ->when($params['nickname'] ?? false, fn($query, $name) => $query->where('nickname', 'like', $name . '%'))
            ->when($params['account'] ?? false, fn($query, $name) => $query->where('account', 'like', $name . '%'));
        $total = (clone $roleModel)->count();
        $list = $roleModel
            ->with('roles')->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get()
            ->makeHidden('password')
            ->toArray();
        return compact('total', 'list');
    }

    /**
     * 新增或更新
     * @throws \Throwable
     */
    public function insertOrUpdate(int $id, array $data): array
    {
        DB::beginTransaction();
        $roles = $data['roles'];
        unset($data['roles']);
        try {
            if ($id) {
                UserModel::query()->where('id', $id)->update($data);
                UserModel::query()->find($id)->roles()->detach();
            } else {
                $data['password'] = password_hash(config('admin-api.default_password'), PASSWORD_DEFAULT);
                $id = UserModel::query()->insertGetId($data);
            }
            UserModel::query()->find($id)->roles()
                ->saveMany(RoleModel::query()->whereIn('id', $roles)->get());
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new Fail($e->getMessage());
        }
        $data['id'] = $id;
        return $data;
    }

    public function resetPassword($id)
    {
        UserModel::query()->where('id', $id)->update(['password' => password_hash(config('admin-api.default_password'), PASSWORD_DEFAULT)]);
    }

    /**
     * 详情
     */
    public function show(int $id): array
    {
        return UserModel::query()->findOrFail($id)->toArray();
    }

    /**
     * 删除
     * @throws \Throwable
     */
    public function delete(array $ids): void
    {
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id = UserModel::User_Admin) continue;
                $roleModel = UserModel::query()->findOrFail($id);
                $roleModel->roles()->detach();
                $roleModel->delete();
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function getUserByAccount(string $account): ?array
    {
        return UserModel::query()->with('roles')->where('account', $account)->first()?->toArray();
    }

    public function update(int $id, array $data):void
    {
        UserModel::query()->where('id', $id)->update($data);
    }
}
